package link.ten_fei.util;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import link.ten_fei.Bean.Doc_User;
import link.ten_fei.service.UserLoginService;
import link.ten_fei.service.UserLoginServiceImpl;

/**
 * 登录过滤器，拦截所有以.action结尾的请求
 */
@WebFilter("*.action")
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 登录放行，走请求本身方法
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		HttpSession session = httpServletRequest.getSession();
		Doc_User user = (Doc_User) session.getAttribute("session_user");
		UserLoginService userLoginService = new UserLoginServiceImpl();
		if (user != null) {
			// 登录
			// 通过reques的httpServletRequest.getRequestURI();来判断用户的请求
			roleJudgment(user, httpServletRequest, httpServletResponse, chain);
//			httpServletRequest.getRequestURI();

//			chain.doFilter(request, response);
		} else {
			// 1.判断cookie中是否有用户信息，即学号与密码
			Cookie cookie = CookieUtil.getCookieByName(httpServletRequest, "cookie_name_pass_judge");
			if (cookie != null) {
				String userAndpass = URLDecoder.decode(cookie.getValue(), "utf-8");
				// 分割用户名与密码通过#
				String[] up = userAndpass.split("#");
				Doc_User user2 = userLoginService.findByNamAndPass(up[0], up[1]);
				// 判断当前用户名与密码是否有效
				if (user2 != null) {
					httpServletRequest.getSession().setAttribute("session_user", user2);
					chain.doFilter(httpServletRequest, httpServletResponse);
				} else {
					// 未登录就跳转到登录页面
					request.getRequestDispatcher("/index.jsp").forward(httpServletRequest, httpServletResponse);
				}
			} else {
				// 未登录就跳转到登录页面
				request.getRequestDispatcher("/index.jsp").forward(httpServletRequest, httpServletResponse);
			}
		}

	}

	private void roleJudgment(Doc_User user, HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, FilterChain chain) throws IOException, ServletException {
		// 获取用户角色Id;
		Integer roleId = user.getDoc_judge();
		// 获取请求地址
		String requestUrl = httpServletRequest.getRequestURI();
		// 防止在浏览器地址栏输入地址访问
		if ((requestUrl.startsWith("/EpsSystem/addUser.action") || requestUrl.startsWith("/EpsSystem/userJdc.action"))
				&& roleId.equals(0)) {
			httpServletRequest.getSession().setAttribute("session_user", user);
			chain.doFilter(httpServletRequest, httpServletResponse);
		} else if (requestUrl.startsWith("/EpsSystem/main.action") || requestUrl.startsWith("/EpsSystem/addMR.action")
				|| requestUrl.startsWith("/EpsSystem/queryMR.action")
				|| requestUrl.startsWith("/EpsSystem/changePwd.action")
				|| requestUrl.startsWith("/EpsSystem/print.action")
				|| requestUrl.startsWith("/EpsSystem/prePrint.action")
				|| requestUrl.startsWith("/EpsSystem/show.action")
				|| requestUrl.startsWith("/EpsSystems/aboutMe.action")) {
			httpServletRequest.getSession().setAttribute("session_user", user);
			chain.doFilter(httpServletRequest, httpServletResponse);
		} else {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			// 两秒后跳转
			httpServletRequest.setAttribute("error", "无法访问");
			httpServletRequest.getRequestDispatcher("/index.jsp").forward(httpServletRequest, httpServletResponse);;
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
